<template>
	<view class="container position-relative">
		<view class="main-conetnt">
			<view class="section-1">
				<template v-if="orderType == 'takein'">
					<list-cell tuiTopRadius class="location" :hover="false">
						<view class="flex-fill d-flex justify-content-between align-items-center">
							<view class="store-name flex-fill">
								{{ store.name }}
								
							</view>
							<view class="uni-list-cell-db">
								{{ store.distance_text }}
							</view>
							<!-- <image src="/static/images/navigator-1.png" class="arrow"></image> -->
						</view>
					</list-cell>
				</template>
				<template v-else>
					<list-cell @click="chooseAddress">
						<view class="w-100 d-flex flex-column">
							<view class="d-flex align-items-center justify-content-between mb-10">
								<view class="font-size-extra-lg text-color-base">{{ address.street }}</view>
							</view>
							<view class="d-flex text-color-assist font-size-sm align-items-center">
								<view class="mr-10">{{ address.accept_name }}</view>
								<view class="mr-10">{{ !address.sex ? '先生' : '女士' }}</view>
								<view>{{ address.mobile }}</view>
							</view>
						</view>
					</list-cell>
				</template>
				<template v-if="orderType == 'takein'">
					<list-cell tuiBottomRadius arrow class="meal-time" :hover="false">
						<view class="flex-fill d-flex justify-content-between align-items-center">
							<view class="title">取餐时间</view>
							<!-- <view class="time">立即用餐</view> -->
							<!-- <view class="uni-list"> -->
								<!-- <view class="uni-list-cell"> -->
									<!-- <view class="uni-list-cell-left">
										当前选择
									</view> -->
									<view class="uni-list-cell-db">
										<picker :value="index" :range="timeArr" @change="bindTimeChange">
											<view class="uni-input">{{timeArr[index]}}</view>
										</picker>
									</view>
								<!-- </view> -->
							<!-- </view> -->
						</view>
					</list-cell>
				</template>
				<template v-else>
					<list-cell :hover="false">
						<view class="w-100 d-flex flex-column">
							<view class="d-flex align-items-center font-size-base text-color-base">
								<view class="flex-fill">预计送达时间</view>
								<view class="mr-10">60分钟</view>
							</view>
						</view>
					</list-cell>
				</template>
			</view>
			<!-- 购物车列表 begin -->
			<view class="section-2">
				<view class="cart">
					<list-cell tuiTopRadius last :hover="false">
						<view class="flex-fill d-flex justify-content-between align-items-center">
							<view>
								<text class="font-weight-bold">商品明细</text>
							</view>
							<view class="eadd" @tap="goAdd">
								<span>继续加餐</span>
							</view>
						</view>
					</list-cell>
					<list-cell  last v-for="(item, index) in cart" :key="index" :hover="false">
						<view class="w-100 d-flex flex-column">
							<view class="d-flex align-items-center mb-10">
								<view class="name-and-props overflow-hidden">
									<view class="img">
										<image :src="item.image" mode=""></image>
									</view>
									<view class="d-flex flex-column align-items-start">
										<view class="text-color-base font-size-base ov">
											{{ item.name }}
										</view>
										<view class="text-truncate text-color-assist fonts" v-if="item.props_text">
											{{ item.props_text }}
										</view>
										
										<view class="text-truncate text-color-assist fonts">x {{ item.number }}</view>
									</view>
								</view>
								<view class="d-flex flex-fill justify-content-end align-items-center text-color-base font-size-lg">
									<view>￥{{ item.price }}</view>
								</view>
							</view>
						</view>
					</list-cell>
					<!-- <template v-if="orderType == 'takeout'">
						<list-cell last v-if="store.packing_fee > 0">
							<view class="w-100 d-flex font-size-base align-items-center justify-content-between">
								<view>包装费</view>
								<view>￥{{ parseFloat(store.packing_fee) }}</view>
							</view>
						</list-cell>
						<list-cell last v-if="store.delivery_cost > 0">
							<view class="w-100 d-flex font-size-base align-items-center justify-content-between">
								<view>配送费</view>
								<view>￥{{ parseFloat(store.delivery_cost) }}</view>
							</view>
						</list-cell>
					</template> -->
				</view>
				<list-cell arrow :hover="false" @click="goToPackages(total)">
					<view class="flex-fill d-flex justify-content-between align-items-center">
						<view class="text-color-base">优惠券</view>
						<view class="text-color-base">{{isLogin && !coupon_title ? member.couponNum + '张优惠券' : coupon_title}}</view>
					</view>
				</list-cell>
				<!-- <list-cell arrow>
					<view class="flex-fill d-flex justify-content-between align-items-center">
						<view class="text-color-base">礼品卡</view>
						<view class="text-color-primary">请选择</view>
					</view>
				</list-cell> -->
				<list-cell tuiBottomRadius last>
					<view class="flex-fill d-flex justify-content-end align-items-center">
						<view>总计￥{{ total }},实付</view>
						<view class="font-size-extra-lg font-weight-bold">￥{{ amount }}</view>
					</view>
				</list-cell>
			</view>
			<!-- 购物车列表 end -->
			<view class="d-flex align-items-center justify-content-start font-size-sm text-color-warning" 
				style="padding: 20rpx 0;">
				<!-- <view class="iconfont iconhelp line-height-100"></view>
				<view>优惠券不与满赠、满减活动共享</view> -->
			</view>
			<!-- 支付方式 begin -->
			<view class="payment">
				<list-cell tuiTopRadius last :hover="false">
					<text>支付方式</text>
				</list-cell>
				<list-cell :hover="false">
					<view class="d-flex align-items-center justify-content-between w-100 disabled">
						<view class="iconfont iconbalance line-height-100 payment-icon"></view>
						<view class="flex-fill">余额支付（余额￥{{  isLogin ? member.balance : 0 }}）</view>
						<view class="font-size-sm" v-if="parseFloat(member.balance) < parseFloat(amount)" @click="payBalance">余额不足，去充值</view>
						<view :class="pay_type_balance" @click="pay_type(1)" v-if="parseFloat(member.balance) > parseFloat(amount)"></view>
					</view>
				</list-cell>
				<list-cell tuiBottomRadius last :hover="false">
					<view class="d-flex align-items-center justify-content-between w-100">
						<view class="iconfont iconwxpay line-height-100 payment-icon" style="color: #7EB73A;"></view>
						<view class="flex-fill">微信支付</view>
						<view :class="pay_type_wx" @click="pay_type(2)"></view>
					</view>
				</list-cell>
			</view>
			<!-- 支付方式 end -->
			<!-- 备注 begin -->
			<list-cell radius last @click="goToRemark">
				<view class="d-flex flex-fill align-items-center justify-content-between overflow-hidden">
					<view class="flex-shrink-0 mr-20">备注</view>
					<view class="text-color-base flex-fill text-truncate text-right">{{ form.remark || '口味、风格' }}</view>
				</view>
			</list-cell>
			<!-- 备注 end -->
		</view>
		<!-- 付款栏 begin -->
		<view class="w-100 pay-box position-fixed fixed-bottom d-flex align-items-center justify-content-between bg-white pay">
			<view class="font-size-sm" style="margin-left: 20rpx;">合计：</view>
			<view class="font-size-lg flex-fill">￥{{ amount }}</view>
			<button class="bg-primary h-100 d-flex align-items-center just-content-center text-color-white font-size-base" style="padding: 0 60rpx;" @tap="submit" v-if="isLogin">
				付款
			</button>
			<button class="bg-primary h-100 d-flex align-items-center just-content-center text-color-white font-size-base" style="padding: 0 60rpx;" @tap="submit" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber" v-if="!phoneNumber && !isLogin">
				登录
			</button>
			<button class="bg-primary h-100 d-flex align-items-center just-content-center text-color-white font-size-base" style="padding: 0 60rpx;" @tap="getPhoneNumber('')" v-if="phoneNumber && !isLogin">
				登录
			</button>
		</view>
		<!-- 付款栏 end -->
		<modal :show="ensureAddressModalVisible" custom :mask-closable="false" :radius="radius" width="90%">
			<view class="modal-content">
				<view class="d-flex justify-content-end">
					<image src="/static/images/pay/close.png" style="width: 40rpx; height: 40rpx;" @tap="ensureAddressModalVisible=false"></image>
				</view>
				<view class="d-flex just-content-center align-items-center" style="margin-bottom: 40px;">
					<view class="font-size-extra-lg text-color-base">请再次确认下单地址</view>
				</view>
				<view class="d-flex font-size-base text-color-base font-weight-bold align-items-center justify-content-between mb-20">
					<view>{{ address.accept_name }} {{ address.sex ? '女士' : '先生' }}</view>
					<view>{{ address.mobile }}</view>
				</view>
				<view class="d-flex font-size-sm text-color-assist align-items-center justify-content-between mb-40">
					<view>{{ address.street + address.door_number }}</view>
					<!-- <button type="primary" size="mini" plain class="change-address-btn">修改地址</button> -->
				</view>
				<button type="primary" class="pay_btn" @tap="pay">确认并付款</button>
			</view>
		</modal>
		<key-words :mix="true" :show_key="show_key" :price="amount" @closeFuc="closeFuc" @getPassword="getPassword"></key-words>
	</view>
</template>

<script>
	import {mapState, mapMutations, mapGetters, mapActions} from 'vuex'
	import listCell from '@/components/list-cell/list-cell'
	import modal from '@/components/modal/modal'
	import orders from '@/api/orders'
	import keyWords from "@/components/bian-keywords/index.vue"
	
	export default {
		components: {
			listCell,
			modal,
			keyWords
		},
		data() {
			return {
				cart: [],
				form: {
					remark: ''
				},
				ensureAddressModalVisible: false,
				phone:'',
				coupon_id:0,
				coupon_title:'',
				send_time:'',
				radius:'0',
				coupon_price:0,
				pay_type_balance:'iconfont iconradio-button-on line-height-100 checkbox checked',
				pay_type_wx:'iconfont iconradio-button-off line-height-100 checkbox',
				payType:1,
				show_key:false,
				timeArr: ['立即取餐','10分钟', '20分钟', '30分钟', '40分钟', '50分钟', '60分钟'],
				index: 0,
				scoupon:[],
				phoneNumber:''
			}
		},
		computed: {
			...mapState(['orderType', 'address', 'store','member']),
			...mapGetters(['isLogin']),
			total() {
				if (!this.cart) {
					return 0
				}
				return this.cart.reduce((acc, cur) => acc + cur.number * cur.price, 0)
			},
			amount() {
				if (!this.cart) {
					return 0
				}
				return (this.cart.reduce((acc, cur) => acc + cur.number * cur.price, 0) - (this.coupon_price)).toFixed(2)
			}
		},
		onLoad(option) {
			this.cart = uni.getStorageSync('cart')
			this.phone = this.member.mobilePhone
		},
		onShow() {
			const remark = uni.getStorageSync('remark')
			remark && this.$set(this.form, 'remark', remark)
			this.scoupon = uni.getStorageSync('coupon')
			if (this.scoupon) {
				this.coupon_id = this.scoupon.id
				this.coupon_title = this.scoupon.title
				if(this.scoupon.type == 1 && this.scoupon.price){
					this.coupon_price = this.scoupon.price
				}
			}else{
				this.coupon_id = 0
				this.coupon_title = ''
				this.coupon_price = 0
			}
			this.phoneNumber = uni.getStorageSync('getPhoneNumber')
			if (!this.phoneNumber) {
				uni.showLoading({
					title:'授权登录中',
					mask:true
				})
				this.getUserInfo()
			}
		},
		methods: {
			...mapMutations(['SET_ORDER']),
			...mapActions(['setLogin', 'getUserInfo']),
			goToRemark() {
				uni.navigateTo({
					url: '/pages/remark/remark?remark=' + this.form.remark
				})
			},
			chooseAddress() {
				uni.navigateTo({
					url: '/pages/address/address?is_choose=true&scene=pay'
				})
			},
			goToPackages(amount) {
				// console.log(amount)
				uni.navigateTo({
					url: '/pages/coupons/coupons?amount='+amount
				})
			},
			submit() {
				var that = this
				if (!this.isLogin) {
					return uni.showToast({
						icon:'none',
						title:'请先登录'
					})
				}
				// 检查优惠券是否可用
				if (this.scoupon && this.scoupon.type == 1) {
					if (parseFloat(this.scoupon.satisfy_price) > parseFloat(this.total)) {
						return uni.showModal({
							title: '金额未满'+this.scoupon.satisfy_price,
							content: '本次下单取消优惠券',
							cancelText:'否',
							confirmText:'是',
							success: function (res) {
								if (res.confirm) {
									that.scoupon = []
									that.coupon_id = 0
									that.coupon_title = ''
									that.coupon_price = 0
									that.submit()
									// console.log('用户点击确定');
								} else if (res.cancel) {
									// console.log('用户点击取消');
									uni.showToast({
										icon:'none',
										title:'请取消优惠券或继续加餐'
									})
								}
							}
						});
					}
				}
				if(this.orderType == 'takeout') {
					this.ensureAddressModalVisible = true
				} else {
					this.pay()
				}
			},
			pay() {
				// console.log(this.member.pay_pass)
				//提交订单
				if(this.payType == 1){
					if (parseFloat(this.member.balance) < parseFloat(this.amount)) {
						this.payType = 2
						this.pay_type_wx = 'iconfont iconradio-button-on line-height-100 checkbox checked'
						return this.pay()
					}
					// 如果是密码支付
					let pay_pass = this.member.pay_pass
					if (!pay_pass) {
						// 没有密码
						uni.showModal({
							content: '您还没有设置支付密码',
							success: function (res) {
								if (res.confirm) {
									uni.navigateTo({
										url:'/pages/mine/userinfo'
									})
								} else if (res.cancel) {
									uni.showToast({
										icon:'none',
										title:'请先设置密码'
									})
								}
							}
						});
					} else {
						this.show_key = true
					} 
					
				}
				if(this.payType == 2){
					//微信支付
					this.$http.post('/pay/pay', {orderType:this.orderType,time:this.timeArr[this.index],send_time:this.send_time,phone:this.phone,user_coupon_id:this.coupon_id,cart:this.cart,remark:this.form.remark,address:this.address,payType:this.payType}).then(res => {
						let result = res.data.data //接口返回数据
						console.log(result)
						// 订阅消息
						// this.sendMsg(result.wx_min_template)
						uni.showLoading({}) //拉起支付加载提示
						if (res.data.code == 1) {
							uni.hideLoading()
							uni.requestPayment({
								provider: result.provider,
								timeStamp: result.timeStamp,
								nonceStr: result.nonceStr,
								package: result.package,
								signType:  result.signType,
								paySign:  result.paySign,
								success: () => {
									uni.removeStorageSync('cart')
									uni.removeStorageSync('remark')
									uni.removeStorageSync('coupon')
									uni.hideLoading()
									uni.reLaunch({
										url: '/pages/take-foods/take-foods'
									})
								},
								fail: function (err) {
									// uni.switchTab({
									// 	url:'/pages/mine/mine'
									// })
									// console.log('fail:' + JSON.stringify(err));
								},complete(res) {
									// console.log('complete:' + JSON.stringify(res));
								}
							});
						}else{
							uni.showToast({
								title:res.data.msg,
								icon:'none'
							})
						}
						// console.log(res.data.data)
						// uni.hideLoading()
					}).catch(err => {
					
					})
				}
			},
			bindTimeChange: function(e) {
				this.index = e.detail.value
			},
			pay_type(type){
				if(type == 1){
					this.pay_type_wx = 'iconfont iconradio-button-off line-height-100 checkbox'
					this.pay_type_balance = 'iconfont iconradio-button-on line-height-100 checkbox checked'
				}
				if(type == 2){
					this.pay_type_balance = 'iconfont iconradio-button-off line-height-100 checkbox'
					this.pay_type_wx = 'iconfont iconradio-button-on line-height-100 checkbox checked'
				}
				
				this.payType = type
			},
			getPassword (msg) {
				//请求密码验证
				this.$http.post('/user/payPass', {pay_pass:msg.password}).then(res => {
					if(res.data.code != 1){
						return uni.showModal({
							title: '支付密码错误请重试',
							cancelText:'忘记密码',
							confirmText:'重试',
							success: ({confirm}) =>  {
								console.log(confirm);
								if (confirm) {
									// console.log('用户点击确定');
								} else  {
									uni.navigateTo({
										url:'/pages/mine/userinfo'
									})
								}
							},
							fail:()=>{
								uni.showToast({
									title:'网络错误',
									icon:'none'
								})
							}
						})
					}else{
						uni.showLoading({title: '支付中'})
						// 密码正确
						//余额支付
						this.$http.post('/pay/pay', {orderType:this.orderType,time:this.time,send_time:this.send_time,phone:this.phone,user_coupon_id:this.coupon_id,cart:this.cart,remark:this.form.remark,address:this.address,payType:this.payType}).then(res => {
							if (res.data.code == 0) {
								this.show_key = false
								return uni.showToast({
									title:res.data.msg,
									icon:'none'
								})
							}
							let result = res.data.data //接口返回数据
							// 订阅消息
							this.sendMsg(result.wx_min_template)
							// console.log(res.data.data)
							uni.removeStorageSync('cart')
							uni.removeStorageSync('remark')
							uni.removeStorageSync('coupon')
							uni.hideLoading()
							uni.reLaunch({
								url: '/pages/take-foods/take-foods'
							})
							// uni.hideLoading()
						}).catch(err => {
						
						})
					}
				}).catch(err => {
				
				})
				// console.log(msg)
			},
			closeFuc () {
			    this.show_key = false;
			},
			payBalance(){
				uni.navigateTo({
				    url: '/pages/balance/balance'
				});
			},
			sendMsg(wx_min_template){
				uni.requestSubscribeMessage({
				  tmplIds: [wx_min_template],
				  success:(res)=> { 
					  
					}
				})
			},
			getPhoneNumber(e){
				if (!this.isLogin) {
					this.setLogin(e)
					setTimeout( () => {
						uni.hideLoading()
						uni.showToast({
							icon:'none',
							title:'登录成功'
						})
					}, 500)
				}
			},
			goAdd(){
				// console.log(1111)
				uni.navigateBack({
					delta: 1
				});
			}
		}
	}
</script>
<style lang="scss" scoped>
	.container {
		padding: 20rpx;
		background-color: $bg-color-grey;
		height: 100vh;
		
		.main-conetnt{
			padding-bottom: 160rpx;
		}
	}
	
	.arrow {
		width: 50rpx; 
		height: 50rpx;
		position: relative;
		margin-right: -10rpx;
	}
	
	.location {
		.store-name {
			font-size: $font-size-lg;
		}
		
		.iconfont {
			font-size: 50rpx;
			line-height: 100%;
			color: $color-primary;
		}
	}
	
	.section-1 {
		margin-bottom: 30rpx;
		.contact {
			.contact-tip {
				margin-left: 10rpx;
				border: 2rpx solid $color-primary;
				padding: 6rpx 10rpx;
				color: $color-primary;
			}
		}
	}
	
	.section-2 {
		
		.eadd{
			border: 1px solid $color-primary;
			color: $color-primary;
			padding: 10rpx;
			border-radius: 20rpx;
		}
		
		.name-and-props {
			width: 65%;
			display: flex;
			flex-direction: row;
			
			.img{
				width: 100rpx;
				height: 100rpx;
				
				image{
					width: 100%;
					height: 100%;
				}
			}
			
			.align-items-start{
				justify-content: space-between;
				margin-left: 20rpx;
				
				.ov{
					overflow: hidden;
				}
			}
			
			.fonts{
				font-size: 20rpx;
			}
		}
	}
	
	.payment {
		margin-bottom: 30rpx;
		
		.disabled {
			color: $text-color-grey;
		}
		
		.payment-icon {
			font-size: 44rpx; 
			margin-right: 10rpx;
		}
		
		.checkbox {
			font-size: 36rpx;
			margin-left: 10rpx;
		}
		
		.checked {
			color: $color-primary;
		}
	}
	
	.pay-box {
		box-shadow: 0 0 20rpx rgba(0, 0, 0, .1);
		height: 156rpx;
	}
	
	.modal-content {
		.change-address-btn {
			line-height: 2;
			padding: 0 1em;
		}
		.pay_btn {
			width: 100%;
			border-radius: 50rem !important;
			line-height: 3;
		}
	}
	.text-center{
		text-align: right !important;
	}
</style>
